/*!
 * Avatar JS.
 * 
 * @since: 1.0.0 2017/4/6
 * @author Way Lau <https://waylau.com>
 */
"use strict";
//# sourceURL=main.js
 
// DOM 加载完再执行
$(function() {
	var avatarApi;
    var username;
	// 获取编辑用户头像的界面
	$(".blog-content-container").on("click",".blog-edit-avatar", function () {
        username = $(this).attr("userName")
		avatarApi = "/blog/space/"+ username +"/header";
		$.ajax({ 
			 url: avatarApi, 
			 success: function(data){
				 $("#avatarFormContainer").html(data);
		     },
		     error : function() {
		    	 toastr.error("error!");
		     }
		 });
	});


	// 提交用户头像的图片数据
	$("#submitEditAvatar").on("click", function () { 
		var form = $('#avatarformid')[0];
	    var formData = new FormData(form);   //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数  
	    var base64Codes = $(".cropImg > img").attr("src");

        var csrfToken = $("meta[name='_csrf']").attr("content");
        var csrfHeader = $("meta[name='_csrf_header']").attr("content");
		$.ajax({
		    url: '/blog/file/upload',
		    type: 'post',
		    cache: false,
            beforeSend: function(request) {
                request.setRequestHeader(csrfHeader, csrfToken); // 添加  CSRF Token
            },
		    data: {"base64Code" : base64Codes},
		    success: function(data){
		    	if(data.code == "000"){
                    var avatarUrl = data.data;
				}
		    	// 保存头像更改到数据库
				$.ajax({ 
					 url: avatarApi, 
					 type: 'POST',
					 contentType: "application/json; charset=utf-8",
					 data: JSON.stringify({"id":$("#userId").val(), "header":avatarUrl}),
					 beforeSend: function(request) {
		                 request.setRequestHeader(csrfHeader, csrfToken); // 添加  CSRF Token 
		             },
					 success: function(data){
					 	console.log(data);
						 if (data.success) {
							// 成功后，置换头像图片
							 $(".blog-avatar").attr("src", "http://" + data.data);
                             toastr.success("头像保存成功");
						 } else {
							 toastr.error("error!"+data.msg);
						 }
				     },
				     error : function() {
				    	 toastr.error("位置错误");
				     }
				 });
	        },
		    error : function() {
		    	 toastr.error("error!");
		    }
		})
	});
 

	 
});